﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Project;
using ManagementApi.Mvc.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Commander;
using Modules.Project;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;
using static Modules.Project.ProjectConstants;

namespace ManagementApi.Controllers.CommanderPannel
{
    /// <summary>
    /// 指挥部相关业务接口
    /// </summary>
    [Route("/api/v1/commander/project")]
    [ApiController]
    [Authorize(Roles = "Commander")]
    public class ProjectController : ControllerBase
    {
        private readonly ProjectService projectService;
        private readonly CommanderProjectService commanderProjectService;
        private readonly IMapper mapper;
        private readonly IApplicationContext applicationContext;

        public ProjectController(ProjectService projectService, IMapper mapper, IApplicationContext applicationContext, CommanderProjectService commanderProjectService)
        {
            this.projectService = projectService;
            this.mapper = mapper;
            this.applicationContext = applicationContext;
            this.commanderProjectService = commanderProjectService;
        }

        #region 项目

        /// <summary>
        /// author:hzj date:2024/3/12 describe:完善信息（仅主管登记和平台同步需要完善信息）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("complet_project/{id}")]
        public ApiResult CompletProjectInfo(int id, ProjectCompletForm form)
        {
            ProjectInfo? projectInfo = projectService.GetProjectInfo(id) ?? throw new BusinessException("项目信息不存在");
            mapper.Map(form, projectInfo);
            projectInfo.IsBuilderLicence = true;
            projectInfo.BuilderLicences = form.BuilderLicences;
            projectInfo.BuilderLicencesGrantDate = form.BuilderLicencesGrantDate;
            projectInfo.BuilderLicencesTermDate = form.BuilderLicencesTermDate;
            projectInfo.HasEarnestMoney = form.HasEarnestMoney;
            if (form.HasEarnestMoney)
            {
                projectInfo.EarnestUnitName = form.EarnestUnitName;
                projectInfo.EarnestUnitCode = form.EarnestUnitCode;
                projectInfo.EarnestStartDate = form.EarnestStartDate;
                projectInfo.EarnestEndDate = form.EarnestEndDate;
                projectInfo.EarnestMoney = form.EarnestMoney;
            }
            else
            {
                form.EarnestAttachments = null;
                projectInfo.EarnestUnitName = null;
                projectInfo.EarnestUnitCode = null;
                projectInfo.EarnestStartDate = null;
                projectInfo.EarnestEndDate = null;
                projectInfo.EarnestMoney = null;
            }

            projectService.CompletProjectInfo(projectInfo, form.EarnestAttachments);
            return ApiResult.Success("完善成功");
        }

        /// <summary>
        /// 获取完善信息表单数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        [HttpGet("complet_project/{id}/form")]
        public ApiResult<ProjectCompletForm> GetCompletProjectInfo(int id)
        {
            ProjectInfo? projectInfo = projectService.GetProjectInfo(id) ?? throw new BusinessException("项目信息不存在");
            return ApiResult<ProjectCompletForm>.Success(projectInfo.AsCompletForm(applicationContext));
        }

        /// <summary>
        /// author:hzj date:2023/12/05 describe:项目分页
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("project_page")]
        public ApiResult<PageDto<ProjectInfoDto>> GetProjects([FromQuery] ProjectInfoQuery query, int pageIndex = 1, int pageSize = 20)
        {
            query.CommanderId = applicationContext.CurrentUser?.Id;
            query.AuditStatus = 项目审核状态.通过;
            var pageDto = projectService.GetProjectInfos(query, pageIndex, pageSize).AsPageDto(m => m.AsDto(applicationContext));
            return ApiResult<PageDto<ProjectInfoDto>>.Success(pageDto);
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("base_info/{id}")]
        public ApiResult<ProjectBaseInfo> GetProjectBaseInfo(int id)
        {
            var info = projectService.GetProjectInfo(id);
            if (info == null) return ApiResult<ProjectBaseInfo>.Failure("不存在该项目");
            return ApiResult<ProjectBaseInfo>.Success(info.AsBaseInfo(applicationContext));
        }

        /// <summary>
        /// author:hzj date:2023/12/05 describe:获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("detail/{id}")]
        public ApiResult<ProjectInfoDto> GetProjectInfo(int id)
        {
            var info = projectService.GetProjectInfo(id);
            if (info == null) return ApiResult<ProjectInfoDto>.Failure("不存在该项目");
            ProjectInfoDto projectInfoDto = info.AsDto(applicationContext);
            return ApiResult<ProjectInfoDto>.Success(projectInfoDto);
        }

        /// <summary>
        /// author:hzj date:2023/12/05 describe:删除项目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete/{id}")]
        public ApiResult DeleteProject(int id)
        {
            #region 验证数据权限

            if (applicationContext.CurrentUser == null) throw new BusinessException("登录信息不存在");
            if (!commanderProjectService.ExistsCommanderProject(id, applicationContext.CurrentUser.Id)) throw new OwnAuthorizationFailedException();

            #endregion 验证数据权限

            projectService.Delete(id);
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// author:hzj date:2023/12/05 describe:项目表单数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/projectform")]
        public ApiResult<ProjectRegisterForm> GetProject(int id)
        {
            var data = projectService.GetProjectInfo(id);
            if (data == null)
                return ApiResult<ProjectRegisterForm>.Failure("项目数据不存在");
            return ApiResult<ProjectRegisterForm>.Success(data.AsForm(applicationContext));
        }

        /// <summary>
        /// author:hzj date:2023/12/05 describe:项目下拉
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("pulldown")]
        public ApiResult<PageDto<LabelValue<int>>> GetPulldown([FromQuery] ProjectInfoQuery query, int pageIndex = 1, int pageSize = 9999)
        {
            query.CommanderId = applicationContext.CurrentUser?.Id;
            query.AuditStatus = 项目审核状态.通过;
            var pageDto = projectService.GetProjectInfosByManagerId(query, pageIndex, pageSize);
            var dtos = pageDto.AsPageDto(source => { return source.AsPullDownDto(); });
            return ApiResult<PageDto<LabelValue<int>>>.Success(dtos);
        }

        #endregion 项目
    }
}